import {XgPlayer} from "../index";
import {XgControlPlay} from "./play";
import {XgControlVolume} from "./volume";
import {XgControlTime} from "./time";
import {XgControlDefinitions} from "./definitions";
import {XgControlFullScreen} from "./fullscreen";
import {XgControlSlider} from "./slider";
import {XgControlBarrage} from "./barrage";

export class XgControls {
  show = true;
  controlEl!: HTMLElement;
  sliderInstance!: XgControlSlider;
  playInstance!: XgControlPlay;
  timeInstance!: XgControlTime;
  volumeInstance!: XgControlVolume;
  definitionInstance!: XgControlDefinitions;
  barrageInstance!: XgControlBarrage;
  fullScreenInstance!: XgControlFullScreen;
  constructor(private player: XgPlayer) {
    this.init();
  }
  private init() {
    this.controlEl = document.createElement('div');
    this.controlEl.className = 'controls-wrap controls-wrap-show';
    this.controlEl.innerHTML = `
      <div class="up"></div>
      <div class="down"><div class="left"></div><div class="right"></div></div>
    `;
    this.player.container.appendChild(this.controlEl);
    const upEl = this.controlEl.querySelector('.up');
    const leftEl = this.controlEl.querySelector('.down .left');
    const rightEl = this.controlEl.querySelector('.down .right');
    if (upEl && leftEl && rightEl) {
      this.sliderInstance = new XgControlSlider(this.player);
      upEl.appendChild(this.sliderInstance.root);

      this.playInstance = new XgControlPlay(this.player);
      leftEl.appendChild(this.playInstance.root);
      this.timeInstance = new XgControlTime(this.player);
      leftEl.appendChild(this.timeInstance.root);

      this.volumeInstance = new XgControlVolume();
      rightEl.appendChild(this.volumeInstance.root);

      if (this.player.config.resources.length) {
        this.definitionInstance = new XgControlDefinitions(this.player);
        rightEl.appendChild(this.definitionInstance.root);
      }

      if (this.player.config.barrage.length) {
        this.barrageInstance = new XgControlBarrage(this.player);
        rightEl.appendChild(this.barrageInstance.root);
      }

      this.fullScreenInstance = new XgControlFullScreen(this.player);
      rightEl.appendChild(this.fullScreenInstance.root);
    }
  }
  toggleShow(show: boolean) {
    if (this.show !== show) {
      if (show) {
        this.show = show;
        this.controlEl.classList.add('controls-wrap-show');
      } else {
        if (this.player.playStatus.playing) {
          this.show = show;
          this.controlEl.classList.remove('controls-wrap-show');
        }
      }
    }
  }
}
